package com.starryx.blog.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.starryx.blog.NotFoundException;
import com.starryx.blog.dao.TagMapper;
import com.starryx.blog.po.Tag;
import com.starryx.blog.vo.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by limi on 2017/10/16.
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;


    @Override
    @Transactional
    public int saveTag(Tag tag) {
        return tagMapper.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagMapper.findOneById(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagMapper.findOneByName(name);
    }

    @Override
    public PageInfo<Tag> listTag(Page page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.getOrderBy());
        return new PageInfo<>(tagMapper.findAll());
    }

    @Override
    public List<Tag> listTag() {
        return tagMapper.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        List<Tag> tags = tagMapper.findAll();
        Collections.sort(tags);
        Integer count = tagMapper.count();
        if(size > count){
            return tags.subList(0, count);
        }else{
            return tags.subList(0, size);
        }
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagMapper.findAllByIds(convertToList(ids));
    }

    // 将前端传来的，以 , 隔开的字符串转化为 List 对象
    private List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for (int i=0; i < idarray.length;i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    @Transactional
    public int updateTag(Long id, Tag tag) {
        Tag t = tagMapper.findOneById(id);
        if (t == null) {
            throw new NotFoundException("不存在该标签");
        }
        BeanUtils.copyProperties(tag,t);
        return tagMapper.save(t);
    }

    @Override
    @Transactional
    public void deleteTag(Long id) {
        tagMapper.deleteBlogRelation(id);
        tagMapper.delete(id);
    }
}
